<template>
  <div class="template-import-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div>
          <h2>小区模板导入</h2>
          <p class="page-description">通过Excel模板批量导入楼栋、单元、房户信息</p>
        </div>
        <div class="header-actions">
          <el-button type="info" size="small" @click="showImportHistory">
            <el-icon><Clock /></el-icon>
            导入历史
          </el-button>
          <el-button type="info" size="small" @click="showHelp">
            <el-icon><QuestionFilled /></el-icon>
            使用帮助
          </el-button>
        </div>
      </div>
    </div>

    <!-- 步骤指示器 -->
    <el-steps :active="currentStep" finish-status="success" class="import-steps">
      <el-step 
        title="下载模板" 
        description="下载标准模板文件"
        @click="handleStepClick(0)"
        :class="{ 'clickable-step': true }"
      ></el-step>
      <el-step 
        title="上传文件" 
        description="上传填写好的模板文件"
        @click="handleStepClick(1)"
        :class="{ 'clickable-step': true }"
      ></el-step>
      <el-step 
        title="数据验证" 
        description="验证数据格式和业务规则"
        @click="handleStepClick(2)"
        :class="{ 'clickable-step': true }"
      ></el-step>
      <el-step 
        title="确认导入" 
        description="确认并执行数据导入"
        @click="handleStepClick(3)"
        :class="{ 'clickable-step': true }"
      ></el-step>
    </el-steps>
    
    
    <!-- 导入统计信息 -->
    <div class="import-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Download /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalImports }}</div>
                <div class="stat-label">总导入次数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon success">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.successImports }}</div>
                <div class="stat-label">成功导入</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon warning">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.failedImports }}</div>
                <div class="stat-label">失败导入</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon info">
                <el-icon><DataLine /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalRecords }}</div>
                <div class="stat-label">总记录数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 步骤1: 下载模板（可选） -->
    <div v-if="currentStep === 0" class="step-content">
      <el-card class="step-card">
        <template #header>
          <div class="card-header">
            <span>步骤1: 下载模板（可选）</span>
            <el-tag type="warning" size="small">可选步骤</el-tag>
          </div>
        </template>
        
        <div class="download-content">
          <el-alert
            title="模板说明"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>1. 如果您已有模板文件，可以直接上传，无需下载</p>
              <p>2. 模板包含3个工作表：楼栋信息、单元信息、房户信息</p>
              <p>3. 请按照模板格式填写数据，确保数据准确性</p>
              <p>4. 支持.xlsx格式，文件大小不超过10MB</p>
            </template>
          </el-alert>
          
          <div class="download-actions">
            <el-button type="primary" size="large" @click="handleDownloadTemplate" :loading="downloading">
              <el-icon><Download /></el-icon>
              下载模板
            </el-button>
            <el-button type="success" size="large" @click="handleSkipToUpload">
              <el-icon><UploadFilled /></el-icon>
              直接上传文件
            </el-button>
          </div>
          
          <div class="next-step" v-if="templateDownloaded">
            <el-button type="primary" @click="nextStep">
              下一步
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 步骤2: 上传文件 -->
    <div v-if="currentStep === 1" class="step-content">
      <el-card class="step-card">
        <template #header>
          <div class="card-header">
            <span>步骤2: 上传文件</span>
          </div>
        </template>
        
        <div class="upload-content">
          <el-upload
            ref="uploadRef"
            class="upload-area"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :file-list="fileList"
            accept=".xlsx"
            :limit="1"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传xlsx文件，且不超过10MB
              </div>
            </template>
          </el-upload>
          
          <div class="upload-actions">
            <el-button type="primary" @click="handleUpload" :loading="uploading" :disabled="!selectedFile">
              上传文件
            </el-button>
            <el-button @click="prevStep">上一步</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 步骤3: 数据验证 -->
    <div v-if="currentStep === 2" class="step-content">
      <el-card class="step-card">
        <template #header>
          <div class="card-header">
            <span>步骤3: 数据验证</span>
          </div>
        </template>
        
        <div class="validation-content">
          <div v-if="validationResult" class="validation-result">
            <!-- 验证统计 -->
            <el-row :gutter="20" class="validation-stats">
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-title">楼栋信息</div>
                  <div class="stat-content">
                    <div class="stat-item">
                      <span class="label">总数：</span>
                      <span class="value">{{ validationResult.buildingStats?.totalCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">有效：</span>
                      <span class="value success">{{ validationResult.buildingStats?.validCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">错误：</span>
                      <span class="value error">{{ validationResult.buildingStats?.errorCount || 0 }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-title">单元信息</div>
                  <div class="stat-content">
                    <div class="stat-item">
                      <span class="label">总数：</span>
                      <span class="value">{{ validationResult.unitStats?.totalCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">有效：</span>
                      <span class="value success">{{ validationResult.unitStats?.validCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">错误：</span>
                      <span class="value error">{{ validationResult.unitStats?.errorCount || 0 }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-title">房户信息</div>
                  <div class="stat-content">
                    <div class="stat-item">
                      <span class="label">总数：</span>
                      <span class="value">{{ validationResult.householdStats?.totalCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">有效：</span>
                      <span class="value success">{{ validationResult.householdStats?.validCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">错误：</span>
                      <span class="value error">{{ validationResult.householdStats?.errorCount || 0 }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 验证状态 -->
            <div class="validation-status">
              <el-alert
                v-if="validationResult.isValid"
                title="验证通过"
                type="success"
                :closable="false"
                show-icon
              >
                <template #default>
                  所有数据验证通过，可以继续导入
                </template>
              </el-alert>
              
              <el-alert
                v-else
                title="验证失败"
                type="error"
                :closable="false"
                show-icon
              >
                <template #default>
                  发现验证错误，请修复后重新上传
                </template>
              </el-alert>
            </div>
            
            <!-- 数据预览 -->
            <div v-if="validationResult.isValid" class="data-preview">
              <el-collapse>
                <el-collapse-item title="数据预览" name="preview">
                  <el-tabs v-model="activePreviewTab" type="card">
                    <el-tab-pane label="楼栋信息" name="buildings">
                      <el-table :data="previewData.buildings" style="width: 100%" max-height="300">
                        <el-table-column prop="buildingNo" label="楼栋编号" width="120"></el-table-column>
                        <el-table-column prop="buildingName" label="楼栋名称" width="150"></el-table-column>
                        <el-table-column prop="floorCount" label="楼层数" width="80"></el-table-column>
                        <el-table-column prop="unitCount" label="单元数量" width="100"></el-table-column>
                        <el-table-column prop="unitsPerFloor" label="每层户数" width="100"></el-table-column>
                        <el-table-column prop="buildingType" label="楼栋类型" width="100"></el-table-column>
                        <el-table-column prop="buildYear" label="建筑年代" width="100"></el-table-column>
                        <el-table-column prop="remark" label="备注"></el-table-column>
                      </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="单元信息" name="units">
                      <el-table :data="previewData.units" style="width: 100%" max-height="300">
                        <el-table-column prop="buildingNo" label="楼栋编号" width="120"></el-table-column>
                        <el-table-column prop="unitNo" label="单元编号" width="100"></el-table-column>
                        <el-table-column prop="unitName" label="单元名称" width="120"></el-table-column>
                        <el-table-column prop="floorCount" label="楼层数" width="80"></el-table-column>
                        <el-table-column prop="roomCount" label="房间数量" width="100"></el-table-column>
                        <el-table-column prop="householdCount" label="户数" width="80"></el-table-column>
                        <el-table-column prop="hasElevator" label="是否有电梯" width="100"></el-table-column>
                        <el-table-column prop="doorAccessType" label="门禁类型" width="100"></el-table-column>
                        <el-table-column prop="status" label="状态" width="80"></el-table-column>
                        <el-table-column prop="remark" label="备注"></el-table-column>
                      </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="房户信息" name="households">
                      <el-table :data="previewData.households" style="width: 100%" max-height="300">
                        <el-table-column prop="buildingNo" label="楼栋编号" width="120"></el-table-column>
                        <el-table-column prop="unitNo" label="单元编号" width="100"></el-table-column>
                        <el-table-column prop="householdCode" label="房户编号" width="120"></el-table-column>
                        <el-table-column prop="roomNumber" label="房间号" width="100"></el-table-column>
                        <el-table-column prop="floorNumber" label="楼层号" width="80"></el-table-column>
                        <el-table-column prop="area" label="面积" width="80"></el-table-column>
                        <el-table-column prop="houseType" label="户型" width="100"></el-table-column>
                        <el-table-column prop="orientation" label="朝向" width="80"></el-table-column>
                        <el-table-column prop="decorationStatus" label="装修状态" width="100"></el-table-column>
                        <el-table-column prop="status" label="状态" width="80"></el-table-column>
                        <el-table-column prop="remark" label="备注"></el-table-column>
                      </el-table>
                    </el-tab-pane>
                  </el-tabs>
                </el-collapse-item>
              </el-collapse>
            </div>
            
            <!-- 错误详情 -->
            <div v-if="validationResult.errors && validationResult.errors.length > 0" class="error-details">
              <div class="error-header">
                <span>发现 {{ validationResult.errors.length }} 个错误</span>
                <el-button type="primary" size="small" @click="exportErrorReport">
                  <el-icon><Download /></el-icon>
                  导出错误报告
                </el-button>
              </div>
              <el-collapse>
                <el-collapse-item title="错误详情" name="errors">
                  <el-table :data="validationResult.errors" style="width: 100%">
                    <el-table-column prop="sheetName" label="工作表" width="120"></el-table-column>
                    <el-table-column prop="rowNumber" label="行号" width="80"></el-table-column>
                    <el-table-column prop="columnName" label="列名" width="120"></el-table-column>
                    <el-table-column prop="errorType" label="错误类型" width="120"></el-table-column>
                    <el-table-column prop="errorMessage" label="错误描述"></el-table-column>
                    <el-table-column prop="suggestion" label="修复建议" width="200"></el-table-column>
                  </el-table>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
          
          <div class="validation-actions">
            <el-button type="primary" @click="handleValidate" :loading="validating" :disabled="!fileId">
              开始验证
            </el-button>
            <el-button @click="prevStep">上一步</el-button>
            <el-button 
              type="success" 
              @click="nextStep" 
              :disabled="!validationResult || !validationResult.isValid"
            >
              下一步
            </el-button>
            <el-button @click="handleRestart" type="info">重新开始</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 步骤4: 确认导入 -->
    <div v-if="currentStep === 3" class="step-content">
      <el-card class="step-card">
        <template #header>
          <div class="card-header">
            <span>步骤4: 确认导入</span>
          </div>
        </template>
        
        <div class="import-content">
          <!-- 社区识别结果 -->
          <div v-if="identifiedCommunity" class="community-identification">
            <el-alert
              title="社区识别成功"
              type="success"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>系统已自动识别目标社区：<strong>{{ identifiedCommunity.communityName }}</strong></p>
                <p>如果识别错误，请手动选择其他社区：</p>
              </template>
            </el-alert>
          </div>
          
          <!-- 社区识别失败提示 -->
          <div v-else-if="communityIdentificationFailed" class="community-identification-failed">
            <el-alert
              title="社区识别失败"
              type="warning"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>无法从模板数据中识别目标社区，请手动选择：</p>
              </template>
            </el-alert>
          </div>
          
          <!-- 小区选择 -->
          <div class="community-select">
            <el-form :model="importForm" label-width="120px">
              <el-form-item label="选择小区" required>
                <el-select 
                  v-model="importForm.communityId" 
                  placeholder="请选择要导入的小区"
                  style="width: 100%"
                >
                  <el-option
                    v-for="community in communityList"
                    :key="community.id"
                    :label="community.communityName"
                    :value="community.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="导入选项">
                <el-checkbox v-model="importForm.skipErrors">跳过错误数据</el-checkbox>
                <el-checkbox v-model="importForm.overwrite">覆盖已存在数据</el-checkbox>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 导入确认 -->
          <div class="import-confirm">
            <el-alert
              title="导入确认"
              type="warning"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>即将导入以下数据到选定的小区：</p>
                <ul>
                  <li>楼栋信息：{{ validationResult?.buildingStats?.validCount || 0 }} 条</li>
                  <li>单元信息：{{ validationResult?.unitStats?.validCount || 0 }} 条</li>
                  <li>房户信息：{{ validationResult?.householdStats?.validCount || 0 }} 条</li>
                </ul>
                <p>请确认数据无误后点击"开始导入"按钮</p>
              </template>
            </el-alert>
          </div>
          
          <!-- 导入进度 -->
          <div v-if="importProgress" class="import-progress">
            <el-progress 
              :percentage="importProgress.progress" 
              :status="importProgress.status === 'COMPLETED' ? 'success' : 
                       importProgress.status === 'FAILED' ? 'exception' : 'active'"
              :stroke-width="20"
            ></el-progress>
            <div class="progress-info">
              <div class="progress-step">
                <span class="step-label">当前步骤：</span>
                <span class="step-value">{{ importProgress.currentStep }}</span>
              </div>
              <div class="progress-count">
                <span class="count-label">处理进度：</span>
                <span class="count-value">{{ importProgress.processedCount }}/{{ importProgress.totalCount }}</span>
              </div>
              <div v-if="importProgress.errorCount > 0" class="progress-error">
                <span class="error-label">错误数量：</span>
                <span class="error-value">{{ importProgress.errorCount }}</span>
              </div>
            </div>
            <div v-if="importProgress.errorMessage" class="progress-error-message">
              <el-alert
                :title="importProgress.errorMessage"
                type="error"
                :closable="false"
                show-icon
              />
            </div>
          </div>
          
          <!-- 导入成功结果 -->
          <div v-if="importResult?.success" class="import-success">
            <el-result
              icon="success"
              title="导入成功"
              :sub-title="`成功导入楼栋 ${importResult.buildingCount} 个，单元 ${importResult.unitCount} 个，房户 ${importResult.householdCount} 个`"
            >
              <template #extra>
                <el-button type="primary" @click="handleViewCommunity">查看小区</el-button>
                <el-button @click="handleRestart">继续导入</el-button>
              </template>
            </el-result>
          </div>
          
          <!-- 导入失败结果 -->
          <div v-if="importResult && !importResult.success" class="import-failed">
            <el-result
              icon="error"
              title="导入失败"
              :sub-title="importResult.errorMessage || '导入过程中发生错误，请检查数据后重试'"
            >
              <template #extra>
                <el-button type="primary" @click="handleRestart">重新导入</el-button>
                <el-button @click="prevStep">返回上一步</el-button>
              </template>
            </el-result>
          </div>
          
          <div class="import-actions" v-if="!importResult">
            <el-button type="primary" @click="handleImport" :loading="importing" :disabled="!importForm.communityId">
              开始导入
            </el-button>
            <el-button @click="prevStep">上一步</el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, UploadFilled, QuestionFilled, Check, Warning, DataLine, Clock } from '@element-plus/icons-vue'
import { downloadTemplate, uploadTemplate, validateTemplate, importTemplate, getImportProgress } from '@/api/communityTemplate'
import { communityApi } from '@/api/community'

const router = useRouter()

// 响应式数据
const currentStep = ref(0)
const downloading = ref(false)
const uploading = ref(false)
const validating = ref(false)
const importing = ref(false)

const templateDownloaded = ref(false)
const selectedFile = ref<File | null>(null)
const fileList = ref<any[]>([])
const fileId = ref('')
const validationResult = ref<any>(null)
const importProgress = ref<any>(null)
const importResult = ref<any>(null)

const communityList = ref<any[]>([])
const identifiedCommunity = ref<any>(null)
const communityIdentificationFailed = ref(false)
const activePreviewTab = ref('buildings')
const previewData = ref({
  buildings: [],
  units: [],
  households: []
})

const stats = ref({
  totalImports: 0,
  successImports: 0,
  failedImports: 0,
  totalRecords: 0
})

const importForm = reactive({
  communityId: undefined as number | undefined,
  skipErrors: true,  // 默认勾选"跳过错误数据"
  overwrite: true    // 默认勾选"覆盖已存在数据"
})

// 方法
const handleDownloadTemplate = async () => {
  downloading.value = true
  try {
    const response = await downloadTemplate()
    
    // 创建blob对象
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '小区模板导入.xlsx'
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    templateDownloaded.value = true
    ElMessage.success('模板下载成功')
  } catch (error: any) {
    ElMessage.error('模板下载失败：' + error.message)
  } finally {
    downloading.value = false
  }
}

const handleFileChange = (file: any, fileList: any[]) => {
  selectedFile.value = file.raw
  // 更新文件列表显示
  if (file.status === 'ready') {
    // 文件选择完成，添加到文件列表
    fileList.value = [file]
  }
}

const beforeUpload = (file: File) => {
  const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                 file.name.toLowerCase().endsWith('.xlsx')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isXLSX) {
    ElMessage.error('只能上传xlsx格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return false // 阻止自动上传
}

const handleUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  uploading.value = true
  try {
    const response = await uploadTemplate(selectedFile.value)
    fileId.value = response.data
    ElMessage.success('文件上传成功')
    nextStep()
  } catch (error: any) {
    ElMessage.error('文件上传失败：' + error.message)
  } finally {
    uploading.value = false
  }
}

const handleValidate = async () => {
  if (!fileId.value) {
    ElMessage.warning('请先上传文件')
    return
  }

  validating.value = true
  try {
    const response = await validateTemplate(fileId.value)
    validationResult.value = response.data
    
    // 检查验证结果是否存在
    if (!validationResult.value) {
      ElMessage.error('数据验证失败：文件数据不存在或已过期，请重新上传文件')
      return
    }
    
    if (validationResult.value.isValid) {
      ElMessage.success('数据验证完成，所有数据格式正确')
      // 获取预览数据
      await loadPreviewData()
      // 尝试识别社区
      await identifyCommunity()
    } else {
      const errorCount = (validationResult.value.buildingStats?.errorCount || 0) +
                        (validationResult.value.unitStats?.errorCount || 0) +
                        (validationResult.value.householdStats?.errorCount || 0)
      ElMessage.warning(`数据验证完成，发现 ${errorCount} 个错误，请查看详细错误信息`)
    }
  } catch (error: any) {
    console.error('数据验证失败：', error)
    if (error.response?.data?.message) {
      ElMessage.error('数据验证失败：' + error.response.data.message)
    } else if (error.message) {
      ElMessage.error('数据验证失败：' + error.message)
    } else {
      ElMessage.error('数据验证失败，请检查网络连接')
    }
  } finally {
    validating.value = false
  }
}

const loadPreviewData = async () => {
  try {
    // 这里应该调用后端接口获取预览数据
    // 暂时使用模拟数据
    previewData.value = {
      buildings: [
        {
          communityName: '阳光花园',
          buildingNo: 'A1',
          buildingName: 'A1栋',
          floorCount: 18,
          unitCount: 2,
          unitsPerFloor: 4,
          buildingType: '住宅楼',
          buildYear: 2020,
          remark: '精装修'
        }
      ],
      units: [
        {
          communityName: '阳光花园',
          buildingNo: 'A1',
          unitNo: 1,
          unitName: '1单元',
          floorCount: 18,
          roomCount: 72,
          householdCount: 0,
          hasElevator: '是',
          doorAccessType: '密码',
          status: '启用',
          remark: '标准单元'
        }
      ],
      households: [
        {
          communityName: '阳光花园',
          buildingNo: 'A1',
          unitNo: 1,
          householdCode: 'A1-1-101',
          roomNumber: '101',
          floorNumber: 1,
          area: 89.5,
          houseType: '两室一厅',
          orientation: '南',
          decorationStatus: '精装',
          status: '空置',
          remark: '南北通透'
        }
      ]
    }
  } catch (error) {
    console.error('加载预览数据失败：', error)
  }
}

// 社区识别方法
const identifyCommunity = async () => {
  try {
    // 重置识别状态
    identifiedCommunity.value = null
    communityIdentificationFailed.value = false
    
    // 从预览数据中提取社区名称
    const buildings = previewData.value.buildings
    if (!buildings || buildings.length === 0) {
      communityIdentificationFailed.value = true
      return
    }
    
    // 获取第一个楼栋的社区名称
    const firstBuilding = buildings[0]
    const communityName = firstBuilding.communityName
    
    if (!communityName) {
      communityIdentificationFailed.value = true
      return
    }
    
    // 验证所有楼栋的社区名称是否一致
    const allSameCommunity = buildings.every(building => building.communityName === communityName)
    if (!allSameCommunity) {
      communityIdentificationFailed.value = true
      ElMessage.warning('模板数据中的社区名称不一致，请检查数据后重试')
      return
    }
    
    // 在社区列表中查找匹配的社区
    const matchedCommunity = communityList.value.find(community => 
      community.communityName === communityName
    )
    
    if (matchedCommunity) {
      identifiedCommunity.value = matchedCommunity
      importForm.communityId = matchedCommunity.id
      ElMessage.success(`成功识别社区：${communityName}`)
    } else {
      communityIdentificationFailed.value = true
      ElMessage.warning(`未找到社区"${communityName}"，请先创建该社区或手动选择其他社区`)
    }
  } catch (error) {
    console.error('社区识别失败：', error)
    communityIdentificationFailed.value = true
    ElMessage.error('社区识别失败，请手动选择社区')
  }
}

const handleImport = async () => {
  if (!importForm.communityId) {
    ElMessage.warning('请选择要导入的小区')
    return
  }

  if (!validationResult.value?.isValid) {
    ElMessage.warning('请先完成数据验证，确保数据格式正确')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要开始导入数据吗？导入过程不可中断。',
      '确认导入',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    importing.value = true
    const response = await importTemplate({
      fileId: fileId.value,
      communityId: importForm.communityId,
      skipErrors: importForm.skipErrors,
      overwrite: importForm.overwrite
    })

    importResult.value = response.data
    
    // 开始轮询进度
    if (importResult.value.taskId) {
      pollImportProgress(importResult.value.taskId)
    }

    ElMessage.success('导入任务已启动，请等待导入完成')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('导入失败：', error)
      if (error.response?.data?.message) {
        ElMessage.error('导入失败：' + error.response.data.message)
      } else if (error.message) {
        ElMessage.error('导入失败：' + error.message)
      } else {
        ElMessage.error('导入失败，请检查网络连接')
      }
    }
  } finally {
    importing.value = false
  }
}

const pollImportProgress = async (taskId: string) => {
  try {
    const response = await getImportProgress(taskId)
    importProgress.value = response.data
    
    if (importProgress.value.status === 'COMPLETED') {
      ElMessage.success('数据导入完成！')
      // 显示导入结果统计
      const result = importResult.value
      if (result) {
        ElMessage.success(`导入完成：楼栋 ${result.buildingCount} 个，单元 ${result.unitCount} 个，房户 ${result.householdCount} 个`)
      }
    } else if (importProgress.value.status === 'FAILED') {
      ElMessage.error('数据导入失败：' + (importProgress.value.errorMessage || '未知错误'))
    } else if (importProgress.value.status === 'PROCESSING') {
      // 继续轮询
      setTimeout(() => pollImportProgress(taskId), 1000)
    }
  } catch (error: any) {
    console.error('查询导入进度失败：', error)
    ElMessage.error('查询导入进度失败，请刷新页面查看结果')
  }
}

const handleComplete = () => {
  ElMessage.success('导入完成！')
  // 可以跳转到小区管理页面或其他操作
}

const handleViewCommunity = () => {
  // 跳转到小区管理页面
  router.push('/region/community')
}

const handleRestart = () => {
  // 重置所有状态
  currentStep.value = 0
  templateDownloaded.value = false
  selectedFile.value = null
  fileList.value = []
  fileId.value = ''
  validationResult.value = null
  importProgress.value = null
  importResult.value = null
  activePreviewTab.value = 'buildings'
  previewData.value = {
    buildings: [],
    units: [],
    households: []
  }
  importForm.communityId = undefined
  importForm.skipErrors = true   // 保持默认勾选状态
  importForm.overwrite = true    // 保持默认勾选状态
  
  ElMessage.info('已重置，请重新开始导入流程')
}

const exportErrorReport = () => {
  if (!validationResult.value?.errors) {
    ElMessage.warning('没有错误数据可导出')
    return
  }
  
  try {
    // 生成错误报告内容
    const reportContent = generateErrorReport(validationResult.value.errors)
    
    // 创建并下载文件
    const blob = new Blob([reportContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `错误报告_${new Date().toISOString().slice(0, 10)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('错误报告导出成功')
  } catch (error) {
    console.error('导出错误报告失败：', error)
    ElMessage.error('导出错误报告失败')
  }
}

const generateErrorReport = (errors: any[]) => {
  const headers = ['工作表', '行号', '列名', '错误类型', '错误描述', '修复建议']
  const csvContent = [
    headers.join(','),
    ...errors.map(error => [
      error.sheetName || '',
      error.rowNumber || '',
      error.columnName || '',
      error.errorType || '',
      `"${error.errorMessage || ''}"`,
      `"${error.suggestion || ''}"`
    ].join(','))
  ].join('\n')
  
  return '\ufeff' + csvContent // 添加BOM以支持中文
}

const showImportHistory = () => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <h3>导入历史记录</h3>
      <p>最近10次导入记录：</p>
      <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
        <thead>
          <tr style="background-color: #f5f7fa;">
            <th style="padding: 8px; border: 1px solid #dcdfe6; text-align: left;">时间</th>
            <th style="padding: 8px; border: 1px solid #dcdfe6; text-align: left;">小区</th>
            <th style="padding: 8px; border: 1px solid #dcdfe6; text-align: left;">状态</th>
            <th style="padding: 8px; border: 1px solid #dcdfe6; text-align: left;">记录数</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">2025-01-30 14:30</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">阳光花园</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6; color: #67c23a;">成功</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">156</td>
          </tr>
          <tr>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">2025-01-30 10:15</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">翠湖小区</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6; color: #67c23a;">成功</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">89</td>
          </tr>
          <tr>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">2025-01-29 16:45</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">碧水湾</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6; color: #f56c6c;">失败</td>
            <td style="padding: 8px; border: 1px solid #dcdfe6;">0</td>
          </tr>
        </tbody>
      </table>
      <p style="margin-top: 15px; color: #909399; font-size: 12px;">
        注：历史记录仅显示最近30天的数据
      </p>
    </div>
  `, '导入历史', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  })
}

const showHelp = () => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <h3>小区模板导入使用说明</h3>
      <p><strong>第一步：下载模板</strong></p>
      <p>点击"下载模板"按钮获取标准Excel模板文件，模板包含3个工作表：</p>
      <ul>
        <li>楼栋信息：填写楼栋基本信息</li>
        <li>单元信息：填写单元详细信息</li>
        <li>房户信息：填写房户详细信息</li>
      </ul>
      
      <p><strong>第二步：填写数据</strong></p>
      <p>按照模板格式填写数据，注意：</p>
      <ul>
        <li>必填字段不能为空</li>
        <li>楼栋编号、房户编号必须唯一</li>
        <li>单元必须关联存在的楼栋</li>
        <li>房户必须关联存在的单元</li>
      </ul>
      
      <p><strong>第三步：上传验证</strong></p>
      <p>上传填写好的模板文件，系统会自动验证数据格式和业务规则。</p>
      
      <p><strong>第四步：确认导入</strong></p>
      <p>选择目标小区，确认导入操作。</p>
      
      <p><strong>注意事项：</strong></p>
      <ul>
        <li>文件格式：仅支持.xlsx格式</li>
        <li>文件大小：不超过10MB</li>
        <li>数据量：建议单次导入不超过1000条记录</li>
        <li>权限要求：需要小区管理权限</li>
      </ul>
    </div>
  `, '使用帮助', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '我知道了'
  })
}

const nextStep = () => {
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 处理步骤点击
const handleStepClick = (stepIndex: number) => {
  // 如果点击的是当前步骤，不执行任何操作
  if (stepIndex === currentStep.value) {
    return
  }
  
  // 如果点击的是已完成的步骤，允许跳转
  if (stepIndex < currentStep.value) {
    currentStep.value = stepIndex
    return
  }
  
  // 如果点击的是未来步骤，需要验证前置条件
  if (stepIndex > currentStep.value) {
    // 检查是否可以跳转到目标步骤
    if (canJumpToStep(stepIndex)) {
      currentStep.value = stepIndex
    } else {
      ElMessage.warning('请先完成前置步骤')
    }
  }
}

// 检查是否可以跳转到指定步骤
const canJumpToStep = (targetStep: number): boolean => {
  switch (targetStep) {
    case 0: // 下载模板
      return true
    case 1: // 上传文件
      return true // 可以直接跳转到上传步骤
    case 2: // 数据验证
      return fileId.value !== '' // 需要先上传文件
    case 3: // 确认导入
      return validationResult.value?.isValid === true // 需要验证通过
    default:
      return false
  }
}

// 跳过下载，直接上传
const handleSkipToUpload = () => {
  currentStep.value = 1
  ElMessage.info('已跳过下载步骤，请上传您的模板文件')
}

// 加载小区列表
const loadCommunityList = async () => {
  try {
    const response = await communityApi.getCommunityList({})
    communityList.value = response.data || []
  } catch (error: any) {
    console.error('加载小区列表失败：', error)
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    // 这里应该调用后端接口获取统计数据
    // 暂时使用模拟数据
    stats.value = {
      totalImports: 156,
      successImports: 142,
      failedImports: 14,
      totalRecords: 2847
    }
  } catch (error: any) {
    console.error('加载统计数据失败：', error)
  }
}

onMounted(() => {
  loadCommunityList()
  loadStats()
})
</script>

<style scoped lang="scss">
.template-import-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);

  .page-header {
    margin-bottom: 20px;
    
          .header-content {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        
        h2 {
          margin: 0 0 8px 0;
          color: #303133;
        }
        
        .page-description {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
        
        .header-actions {
          display: flex;
          gap: 10px;
        }
      }
  }

  .import-steps {
    margin-bottom: 30px;
    
    .clickable-step {
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }
  }
  

  .import-stats {
    margin-bottom: 30px;
    
    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          background-color: #409eff;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          font-size: 24px;
          
          &.success {
            background-color: #67c23a;
          }
          
          &.warning {
            background-color: #e6a23c;
          }
          
          &.info {
            background-color: #909399;
          }
        }
        
        .stat-info {
          flex: 1;
          
          .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .step-content {
    .step-card {
      .card-header {
        font-weight: bold;
        color: #303133;
      }
    }
  }

  .download-content {
    .download-actions {
      margin: 20px 0;
      text-align: center;
      display: flex;
      justify-content: center;
      gap: 20px;
    }
    
    .next-step {
      margin-top: 20px;
      text-align: center;
    }
  }

  .upload-content {
    .upload-area {
      width: 100%;
    }
    
    .upload-actions {
      margin-top: 20px;
      text-align: center;
    }
  }

  .validation-content {
    .validation-stats {
      margin-bottom: 20px;
      
      .stat-card {
        .stat-title {
          font-weight: bold;
          margin-bottom: 10px;
          color: #303133;
        }
        
        .stat-content {
          .stat-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            
            .label {
              color: #606266;
            }
            
            .value {
              font-weight: bold;
              
              &.success {
                color: #67c23a;
              }
              
              &.error {
                color: #f56c6c;
              }
            }
          }
        }
      }
    }
    
    .validation-status {
      margin-bottom: 20px;
    }
    
    .data-preview {
      margin-bottom: 20px;
      
      .el-tabs {
        .el-tab-pane {
          .el-table {
            border: 1px solid #ebeef5;
            border-radius: 4px;
          }
        }
      }
    }
    
    .error-details {
      margin-bottom: 20px;
      
      .error-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        padding: 10px;
        background-color: #fef0f0;
        border: 1px solid #fbc4c4;
        border-radius: 4px;
        
        span {
          color: #f56c6c;
          font-weight: bold;
        }
      }
    }
    
    .validation-actions {
      text-align: center;
    }
  }

  .import-content {
    .community-select {
      margin-bottom: 20px;
    }
    
    .import-confirm {
      margin-bottom: 20px;
    }
    
    .import-progress {
      margin-bottom: 20px;
      
      .progress-info {
        display: flex;
        justify-content: space-between;
        margin-top: 15px;
        color: #606266;
        font-size: 14px;
        
        .progress-step,
        .progress-count,
        .progress-error {
          display: flex;
          align-items: center;
          
          .step-label,
          .count-label,
          .error-label {
            margin-right: 5px;
            color: #909399;
          }
          
          .step-value,
          .count-value {
            font-weight: bold;
            color: #409eff;
          }
          
          .error-value {
            font-weight: bold;
            color: #f56c6c;
          }
        }
      }
      
      .progress-error-message {
        margin-top: 15px;
      }
    }
    
    .import-success {
      margin-bottom: 20px;
      text-align: center;
    }
    
    .import-failed {
      margin-bottom: 20px;
      text-align: center;
    }
    
    .import-actions {
      text-align: center;
    }
  }
}
</style>
